﻿using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using static System.Console;
using System.Linq;

namespace ImmutableCollectionSample
{
    class Program
    {
        static void Main()
        {
            //SimpleArrayDemo();
            //创建不可变集合
            //ImmutableList<Account> accounts = CreateImmutableList();
            //UsingABuilder(accounts);
            LinqDemo();

            ReadLine();
        }
        //使用LINQ和不变的数组
        public static void LinqDemo()
        {
            ImmutableArray<string> arr = ImmutableArray.Create<string>("one", "two", "three", "four", "five");
            var result = arr.Where(s => s.StartsWith("t"));
            foreach (string str in result)
            {
                Write(str+" ");
            }
        }

        public static void UsingABuilder(ImmutableList<Account> immutableAccounts)
        {
            //使用ImmutableList<T>的ToBuilder方法，转化为可变的集合
            ImmutableList<Account>.Builder builder = immutableAccounts.ToBuilder();
            for (int i = 0; i < builder.Count; i++)
            {
                Account a = builder[i];
                if (a.Amount > 0)
                {
                    builder.Remove(a);
                }
            }
            //使用ToImmutable()方法转化回不可变集合
            ImmutableList<Account> overdrawnAccounts = builder.ToImmutable();

            overdrawnAccounts.ForEach(a => WriteLine($"{a.Name} {a.Amount}"));
        }

        public static ImmutableList<Account> CreateImmutableList()
        {
            var accounts = new List<Account>() {
                new Account("Scrooge McDuck", 667377678765m),
                new Account("Donald Duck", -200m),
                new Account("Ludwig von Drake", 20000m)
            };
            //使用List<T>的ToImmutableList方法，把List<T>对象转换为ImmutableList<T>对象
            ImmutableList<Account> immutableAccounts = accounts.ToImmutableList();

            foreach (var account in immutableAccounts)
            {
                WriteLine($"{account.Name} {account.Amount}");
            }

            immutableAccounts.ForEach(a => WriteLine($"{a.Name} {a.Amount}"));

            return immutableAccounts;
        }

        public static void SimpleArrayDemo()
        {
            //利用Add()方法添加新的不变集合
            ImmutableArray<string> a1 = ImmutableArray.Create<string>();
            ImmutableArray<string> a2 = a1.Add("Williams");
            ImmutableArray<string> a3 =
                a2.Add("Ferrari").Add("Mercedes").Add("Red Bull Racing");
        }
    }
}
